using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class TestShouPaiInteractive_Cursor : MonoBehaviour, IPointerClickHandler
{
    public Camera paiCamera;
    public RawImage renderImage;

    public void OnPointerClick(PointerEventData eventData)
    {
        if (paiCamera == null || renderImage == null || renderImage.texture == null)
        {
            Debug.LogError("PaiCamera, RenderImage, 或 RenderImage.texture 未设置!");
            return;
        }

        // 1. 获取鼠标在RawImage上的本地坐标
        RectTransform rectTransform = renderImage.rectTransform;
        Vector2 localPoint;

        // eventData.pressEventCamera 是触发事件的相机，对于UI通常是主相机或UI相机
        // 如果您的Canvas是Screen Space - Overlay模式，pressEventCamera可能为null，此时第三个参数可以传null
        Camera pressCamera = (renderImage.canvas.renderMode == RenderMode.ScreenSpaceOverlay) ? null : eventData.pressEventCamera;

        if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, pressCamera, out localPoint))
        {
            Debug.LogWarning("点击点不在RawImage范围内。");
            return;
        }

        // 2. 转换为UV坐标 (0到1范围，左下角为(0,0))
        // RectTransform.rect gives coordinates relative to the pivot.
        // We need to adjust localPoint to be relative to the bottom-left of the RawImage rect.
        Rect rect = rectTransform.rect;
        float adjustedX = localPoint.x - rect.x; // rect.x is the x-coordinate of the bottom-left corner relative to pivot
        float adjustedY = localPoint.y - rect.y; // rect.y is the y-coordinate of the bottom-left corner relative to pivot

        float u = adjustedX / rect.width;
        float v = adjustedY / rect.height;

        // 确保UV在0-1范围内 (可选，但有助于调试)
        // u = Mathf.Clamp01(u);
        // v = Mathf.Clamp01(v);

        // 3. 通过棋牌Camera的ViewportPointToRay发射射线
        // UV坐标可以直接用作视口坐标 (Viewport coordinates: 0,0 is bottom-left; 1,1 is top-right)
        Ray ray = paiCamera.ViewportPointToRay(new Vector3(u, v, 0));
        RaycastHit hit;

        // 4. 进行射线检测
        // 建议为棋牌对象设置特定图层(Layer)，并使用LayerMask进行筛选，提高效率和准确性
        // int chessLayerMask = LayerMask.GetMask("YourChessLayerName");
        // if (Physics.Raycast(ray, out hit, Mathf.Infinity, chessLayerMask))
        if (Physics.Raycast(ray, out hit)) // 不使用LayerMask的版本
        {
            Debug.Log("射线击中对象: " + hit.collider.gameObject.name + " 在坐标: " + hit.point);
            // 在这里添加您的选中棋牌的逻辑
            // 例如:
            // ChessPiece piece = hit.collider.gameObject.GetComponent<ChessPiece>();
            // if (piece != null)
            // {
            //     piece.Select();
            // }
        }
        else
        {
            Debug.Log("射线没有击中任何对象 (在棋牌相机的视角下)。");
        }
    }
}
